package com.wind.plugin.openAction;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.components.JBPanel;
import com.wind.plugin.openAction.entity.Action;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;

import javax.swing.*;
import java.awt.*;

// 自定义 XML 编辑界面
public class EditorDialog extends DialogWrapper {

    private RSyntaxTextArea  textArea;
    private com.wind.plugin.openAction.entity.Action action;
    private Project project;
    private CustomTextEditorAi customTextEditorAi;

    protected EditorDialog(Project project,
                           Action action,
                           CustomTextEditorAi customTextEditorAi) {
        super(project);
        this.action = action;
        setTitle("Edit XML File");
        this.customTextEditorAi = customTextEditorAi;
        init();
    }

    @Override
    protected JComponent createCenterPanel() {
        JBPanel panel = new JBPanel(new BorderLayout());

        panel.setPreferredSize(new Dimension(800, 600));

        textArea = new RSyntaxTextArea();
        if ("ftl".equals(action.getActionConfig().getType())){
            textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
        } else if ("groovy".equals(action.getActionConfig().getType())) {
            textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_GROOVY);
        } else {
            textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
        }

        textArea.setCodeFoldingEnabled(true);
        RTextScrollPane sp = new RTextScrollPane(textArea);
        // 创建一个文本区域，用于显示和编辑 XML 内容
        textArea.setText(action.getActionConfig().getContent()); // 初始化为 XML 文件的内容
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));

        panel.add(sp, BorderLayout.CENTER);

        return panel;
    }

    @Override
    protected void doOKAction() {
        // 获取文本区中的内容并保存回原文件
        String modifiedText = textArea.getText();
        try {
            this.action.getActionConfig().setContent(modifiedText);
            this.customTextEditorAi.updateTableModel();
            this.customTextEditorAi.performWriteAction();
            super.doOKAction();
        } catch (Exception ex) {
            Messages.showMessageDialog(getProject(), "Failed to save the file.", "Error", Messages.getErrorIcon());
        }
    }

    private Project getProject() {
        return this.project;
    }

}
